package jbpm.example;

import jbpm.example.workflow.RegistrationAction;
import junit.framework.Assert;
import org.jbpm.JbpmConfiguration;
import org.jbpm.JbpmContext;
import org.jbpm.graph.def.Action;
import org.jbpm.graph.def.ProcessDefinition;
import org.jbpm.graph.exe.ProcessInstance;
import org.jbpm.graph.exe.Token;
import org.jbpm.instantiation.Delegation;
import org.jbpm.jpdl.xml.JpdlXmlReader;

import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * User: goettl
 * Date: 04.03.11
 * Time: 09:01
 */
public class JBPMRunner {
    JbpmConfiguration jbpmGuiceConfiguration;


    public void doRun() {
        jbpmGuiceConfiguration = JbpmConfiguration
                .getInstance();
        JbpmContext jbpmContext = jbpmGuiceConfiguration.createJbpmContext();
        try {
            InputStream resourceAsStream = this.getClass().getResourceAsStream(
                    "/jbpm/example/jbpmguice.workflow/geek-register/processdefinition.GuiceXmlInstantiator");
            Assert.assertNotNull(resourceAsStream);
            JpdlXmlReader s = new JpdlXmlReader(
                    new InputStreamReader(resourceAsStream));
            ProcessDefinition definition = s.readProcessDefinition();
            jbpmContext.deployProcessDefinition(definition);
            ProcessInstance instance = definition.createProcessInstance();
            jbpmContext.save(instance);
            Assert.assertNotNull(instance);
        } finally {
            jbpmContext.close();
        }

        jbpmContext = jbpmGuiceConfiguration.createJbpmContext();
        try {
            ProcessInstance processInstance = jbpmContext.getGraphSession().findProcessDefinition("geek-register", 1).createProcessInstance();
            jbpmContext.save(processInstance);
            Assert.assertNotNull(processInstance);
            ProcessDefinition processDefinition = processInstance.getProcessDefinition();
            Token token = processInstance.getRootToken();
            Assert.assertSame(processDefinition.getStartState(), token.getNode());
            for (int i = 0; i < 6; i++) {
                processInstance.signal();
                Action action = processInstance.getRootToken().getNode().getAction();
                if (action != null) {
                    Delegation actionDelegation = action.getActionDelegation();
                    RegistrationAction injectedActionHandler = (RegistrationAction) actionDelegation.getInstance();
                    Assert.assertNotNull(injectedActionHandler);
                }
            }
        } finally {
            jbpmContext.close();
        }
    }

    public static void main(String[] args) {
        new JBPMRunner().doRun();
    }
}
